package com.lanou3g.ptp.api.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.lanou3g.ptp.api.service.ApiGradeService;
import com.lanou3g.ptp.entity.*;
import com.lanou3g.ptp.grade.service.GradeRoleService;
import com.lanou3g.ptp.grade.service.GradeService;
import com.lanou3g.ptp.taskrole.service.TaskRoleService;
import com.lanou3g.ptp.user.service.UserService;
import com.lanou3g.ptp.utils.PtpResult;
import com.lanou3g.ptp.utils.PtpResultUtils;
import com.lanou3g.ptp.vo.GradeInfo;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ApiGradeServiceImpl implements ApiGradeService {
    @Reference
    private GradeRoleService gradeRoleService;
    @Reference
    private TaskRoleService taskRoleService;
    @Reference
    private GradeService gradeService;
    @Reference
    private UserService userService;


    //  添加一个学生的成绩
    @Override
    public PtpResult addGrade(GradeRole gradeRole) {
        List<GradeRole> gradeRoles = gradeRoleService.findByGradeId(gradeRole.getGradeId());
        ArrayList<Long> list = new ArrayList<>();
        for (GradeRole role : gradeRoles) {
            Long roleId = role.getRoleId();
            list.add(roleId);
        }
        Grade grade = gradeService.findById(gradeRole.getGradeId());
        List<TaskRole> taskRoles = taskRoleService.findByTaskId(grade.getTaskId());
        ArrayList<Long> list1 = new ArrayList<>();
        for (TaskRole taskRole : taskRoles) {
            Long roleId = taskRole.getRoleId();
            list1.add(roleId);
        }
        if (!list.contains(gradeRole.getRoleId()) && list1.contains(gradeRole.getRoleId())) {
            gradeRoleService.addGradeRole(gradeRole);
            List<GradeRole> gradeRoles2 = gradeRoleService.findByGradeId(gradeRole.getGradeId());
            ArrayList<Long> list2 = new ArrayList<>();
            for (GradeRole role2 : gradeRoles2) {
                Long roleId2 = role2.getRoleId();
                list2.add(roleId2);
            }
            if (list2.size() == list1.size()) {
                for (Long aLong : list2) {
                    if (list1.contains(aLong)) {
                        List<GradeRole> gradeRoles1 = gradeRoleService.findByGradeId(gradeRole.getGradeId());
                        Double sum = 0d;
                        for (GradeRole gradeRole1 : gradeRoles1) {
                            Long roleId = gradeRole1.getRoleId();
                            TaskRole taskRole = taskRoleService.findByRoleId(roleId);
                            Double ratio = taskRole.getRatio();
                            Integer score = gradeRole1.getScore();
                            Double sum1 = ratio * score;
                            sum = sum + sum1;
                        }
                        grade.setScore(sum);
                        gradeService.updateGrade(grade);
                    }
                }
                return PtpResultUtils.ok("打分结束");
            } else {
                return PtpResultUtils.ok("打分成功");
            }
        } else if (list.contains(gradeRole.getRoleId())) {
            return PtpResultUtils.error(500, "请勿重复打分");
        } else {
            return PtpResultUtils.error(500, "抱歉，您不在该次任务的打分范围内");
        }
    }

    //    根据id删除学生信息
    @Override
    public PtpResult deleteById(Long id) {
        GradeRole gradeRole = gradeRoleService.findById(id);
        Grade grade = new Grade();
        grade.setId(gradeRole.getGradeId());
        grade.setScore(0.00);
        gradeService.updateGrade(grade);
        gradeRoleService.deleteById(id);
        return PtpResultUtils.ok("删除成功");
    }

    //    更改学生的成绩
    @Override
    public PtpResult update(GradeRole gradeRole) {
        gradeRoleService.updateById(gradeRole);
        GradeRole gradeRole2 = gradeRoleService.findById(gradeRole.getId());
        List<GradeRole> gradeRoles1 = gradeRoleService.findByGradeId(gradeRole2.getGradeId());
        Double sum = 0d;
        for (GradeRole gradeRole1 : gradeRoles1) {
            Long roleId = gradeRole1.getRoleId();
            TaskRole taskRole = taskRoleService.findByRoleId(roleId);
            Double ratio = taskRole.getRatio();
            Integer score = gradeRole1.getScore();
            Double sum1 = ratio * score;
            sum = sum + sum1;
        }
        Grade grade = new Grade();
        grade.setId(gradeRole2.getGradeId());
        grade.setScore(sum);
        gradeService.updateGrade(grade);
        return PtpResultUtils.ok("修改成功");
    }


    @Override
    public InputStream findAll() {
        //查询所有成绩
        List<Grade> grades = gradeService.findAll();
        for (Grade grade : grades) {
            //获取成绩学生id
            Long studentId = grade.getStudentId();
            //查询用户
            User user = userService.userById(studentId);
            //获取学生名字
            grade.setName(user.getName());
        }

        HSSFWorkbook sheets = new HSSFWorkbook();//创建一个新工作浦
        Sheet sheet = sheets.createSheet("码页");

        CreationHelper creationHelper = sheets.getCreationHelper();

        //创建单元格样式  负责表格时间格式
        CellStyle cellStyle = sheets.createCellStyle();
        cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd hh:mm:ss")); //设置时间样式

        //负责表格对齐方式
        CellStyle cellStyle1 = sheets.createCellStyle();
        cellStyle1.setAlignment(HorizontalAlignment.LEFT);//设置单元格水平方向对齐方式  居中
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);//设置单元格垂直方向对齐方式  居中

        //设置字体样式风格
        HSSFCellStyle cellStyle2 = sheets.createCellStyle();
        HSSFFont font = sheets.createFont();  //设置字体样式
        font.setFontName("微软雅黑");
        font.setFontHeightInPoints((short) 16);//设置字号
        font.setColor(HSSFColor.HSSFColorPredefined.RED.getIndex());//设置字体颜色
        cellStyle2.setFont(font);  //字体风格放入  风格

        //设置表头字体样式
        HSSFCellStyle cellStyle4 = sheets.createCellStyle();
        HSSFFont font1 = sheets.createFont();  //设置字体样式
        font1.setFontName("微软雅黑");
        font1.setFontHeightInPoints((short) 12);//设置字号
        font1.setColor(HSSFColor.HSSFColorPredefined.BLUE.getIndex());//设置字体颜色
        cellStyle4.setFont(font1);  //字体风格放入  风格

        Row row1 = sheet.createRow(0);
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        row1.setHeightInPoints(30);//设置行的高度是50
        row1.createCell(0).setCellValue("姓名");
        row1.createCell(1).setCellValue("分数");
        row1.setRowStyle(cellStyle1);
        row1.setRowStyle(cellStyle4);

        int i = 1;
        for (Grade grade : grades) {
            Row row = sheet.createRow(i);
            sheet.setColumnWidth(0, 20 * 256);
            sheet.setColumnWidth(1, 30 * 256);
            row.setHeightInPoints(30);//设置行的高度是50


            //兑换券名字
            Cell cell3 = row.createCell(0);
            cell3.setCellValue(grade.getName());
            cell3.setCellStyle(cellStyle1);
            cell3.setCellStyle(cellStyle2);


            //学生成绩
            Cell cell4 = row.createCell(1);
            cell4.setCellValue(grade.getScore());
            cell4.setCellStyle(cellStyle1);
            cell4.setCellStyle(cellStyle2);
            cell4.setCellStyle(cellStyle);

            i++;
        }
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        try {
            sheets.write(bo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //ByteArrayInputStream inputStream = new ByteArrayInputStream(bo.toByteArray());
        return new ByteArrayInputStream(bo.toByteArray());
    }

    @Override
    @Transactional
    public boolean grade(Teacher teacher, GradeItem gradeItem) {
        int score = calculate(gradeItem);
        GradeRole gradeRole = new GradeRole();
        List<GradeRole> repetition = null;
        if (score != 0) {
            Grade grades = new Grade();
            grades.setStudentId(gradeItem.getStudentId());
            grades.setTaskId(gradeItem.getTaskId());
            Long studentBoorId = taskRoleService.selectStudent(gradeItem.getStudentId(), gradeItem.getTaskId());
            Long uid = null;
            if (studentBoorId != null) {
                List<GradeRole> scoreRole = taskRoleService.selectScore(studentBoorId);
                repetition = taskRoleService.addBoolean(teacher.getRole(), studentBoorId);
                if (repetition.size() != 0) {
                    result(studentBoorId, gradeItem.getTaskId());
                    return false;
                } else {
                    score = calculate(gradeItem);
                    gradeRole.setGradeId(studentBoorId);
                    gradeRole.setCreateTime(new Date());
                    gradeRole.setUpdateTime(new Date());
                    gradeRole.setScore(score);
                    gradeRole.setEvaluate(gradeItem.getRemark());
                    gradeRole.setRoleId(Long.valueOf(teacher.getRole()));
                }
            } else {
                repetition = taskRoleService.addBoolean(teacher.getRole(), studentBoorId);
                if (repetition.size() != 0) {

                    result(studentBoorId, gradeItem.getTaskId());
                    return false;
                } else {
                    uid = taskRoleService.addGrage(grades);
                    gradeRole.setGradeId(uid);
                    gradeRole.setCreateTime(new Date());
                    gradeRole.setUpdateTime(new Date());
                    gradeRole.setEvaluate(gradeItem.getRemark());

                    gradeRole.setScore(score);

                    gradeRole.setRoleId(Long.valueOf(teacher.getRole()));

                }
            }
            boolean flag = taskRoleService.addGrageRole(gradeRole);

            result(studentBoorId, gradeItem.getTaskId());
            return flag;

        }


        return false;
    }


    @Override
    public boolean addEvaluatingTeacher(Long id, Integer score, Long taskId) {
        Task task = taskRoleService.findTask(taskId);
        GradeTeacher teacher = taskRoleService.findByStudentIdAndTaskId(id, taskId);
        GradeTeacher gradeTeacher = new GradeTeacher();
        if (teacher != null) {
            return false;
        } else {
            gradeTeacher.setBaseTeacherId(task.getBaseTeacherId());
            gradeTeacher.setScore(score);
            gradeTeacher.setStudentId(id);
            gradeTeacher.setTaskId(taskId);
            int i = gradeService.addGradeTeacher(gradeTeacher);
            if (i > 0) {
                return true;
            } else {
                return false;
            }
        }
    }

    @Override
    public GradeInfo getMyGradeInfo(Student student, Long taskId) {
        GradeInfo gradeInfo = new GradeInfo();
        Long studentId = student.getId();
        // TODO 2019.11.06 未完成
//        if (!checkTaskEnd(taskId)) {
//            gradeInfo.setState(0);
//            gradeInfo.setMessage("任务尚未结束");
//        } else if (checkEvaluating(studentId, taskId)) {
//            Grade grade = gradeService.findByTaskIdAndStudentId(taskId, studentId);
//            if (grade == null || grade.getScore() == null) {
//
//            }
//        } else {
//            gradeInfo.setState(0);
//            gradeInfo.setMessage("尚未评教");
//        }
        return gradeInfo;
    }

    public int calculate(GradeItem gradeItem) {
        int score = 0;
        for (Grades grad : gradeItem.getGrades()) {
            Double standard = taskRoleService.selectRatio(gradeItem.getTaskId(), (long) grad.getGradeItemId());
            score += standard * grad.getScore();
        }
        return score;
    }


    public void result(long grade, long tskId) {
        List<GradeRole> resultScore = taskRoleService.addBoolean(null, grade);
        if (resultScore.size() == 2) {
//      List<TaskRole> proportions= taskRoleService.proportion(tskId);
            int score = 0;
            System.out.println("数据1" + resultScore);

            for (int i = 0; i < resultScore.size(); i++) {

                List<TaskRole> proportions = taskRoleService.proportion(tskId, resultScore.get(i).getRoleId());


                score += resultScore.get(i).getScore() * proportions.get(0).getRatio();

            }
            taskRoleService.updateScore(resultScore.get(0).getGradeId(), score);
        }
    }

}


